package com.example.fengyungo.activity.me;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.example.fengyungo.R;
import com.example.fengyungo.activity.BaseActivity;
import com.example.fengyungo.constant.CodeConstant;
import com.example.fengyungo.constant.DriverConstant;
import com.example.fengyungo.constant.OssConstant;
import com.example.fengyungo.constant.ResultConstant;
import com.example.fengyungo.domain.Driver;
import com.example.fengyungo.utils.BitmapUtils;
import com.example.fengyungo.utils.OkHttpUtils;
import com.example.fengyungo.utils.OssUtils;
import com.example.fengyungo.utils.PermissionUtil;
import com.example.fengyungo.utils.SharedPreferencesUtils;
import com.example.fengyungo.utils.ThreadPoolUtil;
import com.google.android.material.card.MaterialCardView;

/**
 * 个人资料
 *
 * @author XLR
 */
public class MyInfoActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MyInfoActivity";

    /**
     * 头像
     */
    String avatar;
    /**
     * 昵称
     */
    String nickname;
    /**
     * 用户名，账号
     */
    String username;
    /**
     * 性别
     */
    String sex;
    /**
     * 电话号码
     */
    String phone;
    /**
     * 邮箱
     */
    String mail;
    /**
     * 头像图片
     */
    ImageView avatarImageView;
    /**
     * 昵称TextView
     */
    TextView nicknameTextView;
    /**
     * 用户名，账号TextView
     */
    TextView usernameTextView;
    /**
     * 性别TextView
     */
    TextView sexTextView;
    /**
     * 电话号码TextView
     */
    TextView phoneTextView;
    /**
     * 邮箱TextView
     */
    TextView mailTextView;
    /**
     * 返回按钮
     */
    ImageButton back;
    /**
     * 司机
     */
    Driver driver;
    /**
     * 昵称
     */
    MaterialCardView nicknameCard;
    /**
     * 性别
     */
    MaterialCardView sexCard;
    /**
     * 电话号码
     */
    MaterialCardView phoneCard;
    /**
     * 账号
     */
    MaterialCardView usernameCard;
    /**
     * 头像
     */
    MaterialCardView avatarCard;
    /**
     * 邮箱
     */
    MaterialCardView mailCard;
    /**
     * 选择的头像的路径
     */
    String picturePath;
    /**
     * 头像的名称
     */
    String objectName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);

        avatarImageView = findViewById(R.id.avatar);
        nicknameTextView = findViewById(R.id.nickname);
        usernameTextView = findViewById(R.id.username);
        sexTextView = findViewById(R.id.sex);
        phoneTextView = findViewById(R.id.phone);
        mailTextView = findViewById(R.id.mail);

        // 将用户信息更新到TextView
        setMyInfo();

        back = findViewById(R.id.back);
        back.setOnClickListener(this);

        // 修改个人信息的跳转
        // 昵称
        nicknameCard = findViewById(R.id.nickname_card);
        nicknameCard.setOnClickListener(this);
        // 性别
        sexCard = findViewById(R.id.sex_card);
        sexCard.setOnClickListener(this);
        // 电话号码
        phoneCard = findViewById(R.id.phone_card);
        phoneCard.setOnClickListener(this);
        // 头像
        avatarCard = findViewById(R.id.avatar_card);
        avatarCard.setOnClickListener(this);
        // 账号（用户名）
        usernameCard = findViewById(R.id.username_card);
        usernameCard.setOnClickListener(this);
        // 邮箱
        mailCard = findViewById(R.id.mail_card);
        mailCard.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: resultCode=" + resultCode);
        // 如果修改成功则刷新页面
        if (requestCode == CodeConstant.TO_EDIT_MY_INFO_ACTIVITY) {
            if (resultCode == CodeConstant.EDIT_SUCCESS) {
                Log.d(TAG, "onActivityResult: EDIT_SUCCESS");
                setMyInfo();
            }
        } else if (requestCode == CodeConstant.SELECT_PHOTO) {
            if (resultCode == RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                Log.d(TAG, "onActivityResult: selectedImage=" + selectedImage);
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                Log.d(TAG, "onActivityResult: picturePath=" + picturePath);
                // 上传图片到OSS
                Log.d(TAG, "changeAvatar: picturePath=" + picturePath);
                uploadImage(picturePath);
                // 修改SharedPreferences中的头像
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                BitmapUtils.saveBitmapToSharedPreferences(bitmap, this, DriverConstant.AVATAR);
                // 刷新，设置头像
                BitmapDrawable avatarDrawable = new BitmapDrawable(getResources(), bitmap);
                avatarImageView.setBackground(avatarDrawable);
                // 修改数据库中头像的路径
                updateAvatar();
            }
        }
    }

    /**
     * 将用户信息更新到TextView
     */
    private void setMyInfo() {
        // 获取用户信息
        driver = SharedPreferencesUtils.getDriverInfo(this);
        Log.d(TAG, "onCreate: driver=" + driver);
        nickname = driver.getNickname();
        username = driver.getUsername();
        sex = driver.getSex();
        phone = driver.getPhone();
        mail = driver.getMail();

        // 头像设置
        Bitmap bitmapAvatar = BitmapUtils.getBitmapFromSharedPreferences(this, DriverConstant.AVATAR);
        BitmapDrawable avatarDrawable = new BitmapDrawable(getResources(), bitmapAvatar);
        avatarImageView.setBackground(avatarDrawable);
        nicknameTextView.setText(nickname);
        usernameTextView.setText(username);
        sexTextView.setText(sex);
        phoneTextView.setText(phone);
        mailTextView.setText(mail);
    }

    /**
     * 点击事件
     *
     * @param view View
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.nickname_card) {
            toEditMyInfoActivity(DriverConstant.EDIT_NICKNAME);
        } else if (id == R.id.sex_card) {
            toEditMyInfoActivity(DriverConstant.EDIT_SEX);
        } else if (id == R.id.phone_card) {
            toEditMyInfoActivity(DriverConstant.EDIT_PHONE);
        } else if (id == R.id.avatar_card) {
            changeAvatar();
        } else if (id == R.id.username_card) {
            Toast.makeText(MyInfoActivity.this, getString(R.string.cannot_edit), Toast.LENGTH_SHORT).show();
        } else if (id == R.id.mail_card) {
            Toast.makeText(MyInfoActivity.this, getString(R.string.cannot_edit), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 跳转到修改资料的页面
     *
     * @param attribute 要修改的属性
     */
    private void toEditMyInfoActivity(int attribute) {
        Intent intent = new Intent(MyInfoActivity.this, EditMyInfoActivity.class);
        // 设置要修改的属性
        intent.putExtra(DriverConstant.EDIT_ATTRIBUTE, attribute);
        startActivityForResult(intent, CodeConstant.TO_EDIT_MY_INFO_ACTIVITY);
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 动态获取权限
            PermissionUtil.getPermission(this);
            return;
        }
        //Intent.ACTION_PICK 从数据中选择一个项目 (item)，将被选中的项目返回。
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI 获取外部的URI
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, CodeConstant.SELECT_PHOTO);
    }

    /**
     * 修改头像
     */
    private void changeAvatar() {
        // 打开相册
        openAlbum();
        // 在onActivityResult上传图片到OSS、修改SharedPreferences中、修改数据库中头像的路径
    }

    /**
     * 修改数据库中头像的路径
     */
    private void updateAvatar() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String url = DriverConstant.URL_USER_DRIVER + "/updateDriver";
                JSONObject driverJson = new JSONObject();
                String avatarUrl = OssConstant.URL + objectName;
                driverJson.put(DriverConstant.AVATAR, avatarUrl);
                driverJson.put(DriverConstant.ID, driver.getId());
                String driverJsonString = driverJson.toJSONString();
                try {
                    String responseData = OkHttpUtils.put(url, driverJsonString);
                    org.json.JSONObject jsonObject = new org.json.JSONObject(responseData);
                    int code = jsonObject.getInt(ResultConstant.CODE);
                    String msg = jsonObject.getString(ResultConstant.MSG);
                    Log.d(TAG, "run: code:" + code);
                    if (code == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MyInfoActivity.this, getString(R.string.avatar_edit_success), Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MyInfoActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MyInfoActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 将头像上传
     */
    private void uploadImage(String uploadFilePath) {
        Log.d(TAG, "uploadImage: uploadFilePath=" + uploadFilePath);
        int indexOfPoint = uploadFilePath.lastIndexOf('.');
        String img = uploadFilePath.substring(indexOfPoint);
        Log.d(TAG, "uploadImage: img=" + img);
        objectName = DriverConstant.AVATAR + driver.getId() + img;
        Log.d(TAG, "uploadImage: objectName=" + objectName);
        OssUtils.upload(this, objectName, uploadFilePath);
    }

}